package Text4;

import java.util.*;

public class Main {
    public static final int N = 6;
    public static char[][] arr = new char[N][N];
    public static char[][] backup = new char[N][N];
    static int[] dx = {0, -1, 0, 1, 0};
    static int[] dy = {0, 0, 1, 0, -1};
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        while (n-- > 0) {
            int res=10;
            for (int i = 0; i < 5; i++) {
                arr[i] = scanner.next().toCharArray();
            }
            //第一行一共有2^5种按法
            for (int op = 0; op < 32; op++) {
                //备份
                for (int i = 0; i < 5; i++) {
                    backup[i]=arr[i].clone();
                }
                int step = 0;
                //第一行
                for (int i = 0; i < 5; i++) {
                    if ((op >> i & 1) == 1) {
                        turn(0,i);
                        step++;
                    }
                }
                //每一行决定后面一行的操作
                for (int i = 0; i < 4; i++) {
                    for (int j = 0; j < 5; j++) {
                        if(arr[i][j]=='0'){
                            turn(i+1,j);
                            step++;
                        }
                    }
                }
                //判断最后一行
                boolean dark=false;
                for (int i = 0; i < 5; i++) {
                    if(arr[4][i]=='0'){
                        dark=true;
                        break;
                    }
                }
                if(!dark){
                    res=Math.min(res,step);
                }
                //备份
                for (int i = 0; i < 5; i++) {
                    arr[i]=backup[i].clone();
                }
            }
            if(res>6){
                res=-1;
            }
            System.out.println(res);
        }
    }

    private static void turn(int x, int y) {
        for (int i = 0; i < 5; i ++ )
        {
            int a = x + dx[i], b = y + dy[i];
            if (a < 0 || a >= 5 || b < 0 || b >= 5) continue; // 在边界外，直接忽略即可
            arr[a][b] ^= 1;
        }
    }
}
